package com.example.music.metadata;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.id3.ID3v1Tag;

import java.io.File;
import java.io.IOException;

/**
 * @author hanfeng 2019/9/25 12:38
 * @version 0.0.1
 */
public class AudioParse {

    public static File getFile(String path) {
        return new File(path);
    }

    public static AudioFile getAudioFile(File mp3File) {
        try {
            return AudioFileIO.read(mp3File);
        } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMp3Name(AudioFile audioFile) {
        ID3v1Tag tag = ((MP3File) audioFile).getID3v1Tag();
        return createFormatName(tag.getArtist().get(0).toString(), tag.getFirstTitle(), ".mp3");
    }

    public static String getFlacName(AudioFile audioFile) {
        Tag tag = audioFile.getTag();
        String artist = tag.getFields("ARTIST").get(0).toString();
        String title = tag.getFields("TITLE").get(0).toString();
        return createFormatName(artist, title, audioFile.getAudioHeader().getEncodingType().split("\\s")[0].toLowerCase());
    }

    public static String getMusicName(AudioFile audioFile) {
        if (audioFile instanceof MP3File) {
            return getMp3Name(audioFile);
        } else {
            return getFlacName(audioFile);
        }
    }

    public static String getMusicName(File file) {
        AudioFile audioFile = getAudioFile(file);
        if (audioFile instanceof MP3File) {
            return getMp3Name(audioFile);
        } else {
            return getFlacName(audioFile);
        }
    }

    /**
     * 创建格式化文件名
     *
     * @param artist 专辑名
     * @param title  歌曲名
     * @param suffix 后缀
     * @return
     */
    public static String createFormatName(String artist, String title, String suffix) {
        return artist + "-" + title + "." + suffix;
    }
}
